package com.tianxiabuyi.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.BitSet;

/**
 * 编码解码工具类
 *  Created by yang on 2015/5/15.
 */
public final class URLEncodeUtil {
    /** 不需要编码的字符 **/
    static BitSet dontNeedEncoding;

    static {
        dontNeedEncoding = new BitSet(256);
        int i;
        for (i = 'a'; i <= 'z'; i++) {
            dontNeedEncoding.set(i);
        }
        for (i = 'A'; i <= 'Z'; i++) {
            dontNeedEncoding.set(i);
        }
        for (i = '0'; i <= '9'; i++) {
            dontNeedEncoding.set(i);
        }
        dontNeedEncoding.set(' ');
        dontNeedEncoding.set('-');
        dontNeedEncoding.set('_');
        dontNeedEncoding.set('.');
        dontNeedEncoding.set('*');
        dontNeedEncoding.set('+');
        dontNeedEncoding.set('%');
    }

    private URLEncodeUtil () {
    }

    /**
     * 判断段落文本是否被urlencode过
     */
    public static final boolean isURLEncoded(String source) {
        if (source == null || "".equals(source)) {
            return false;
        }
        char[] chars = source.toCharArray();
        boolean containsPercent = false;
        for (char c : chars) {
            if (Character.isWhitespace(c)) {
                return false;
            }
            if (!dontNeedEncoding.get(c)) {
                return false;
            }
            if (c == '%') {
                containsPercent = true;
            }
        }
        if (!containsPercent) {
            return false;
        }
        return true;
    }

    /**
     * URL编码
     * @param URL 要编码的URL
     * @param encode 字符编码
     * @return 编码后的URL
     */
    public static final String encodeURL(String URL, String encode) {
        try {
            return URLEncoder.encode(URL, encode);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用UTF-8对URL编码
     * @param URL 要编码的URL
     * @return 编码后的URL
     */
    public static final String encodeURL(String URL) {
        return encodeURL(URL, StringUtil.UTF8);
    }

    /**
     * 解码URL
     * @param URL 要解码的URL
     * @param encode 字符编码
     * @return 解码后的URL
     */
    public static final String decodeURL(String URL, String encode) {
        try {
            return URLDecoder.decode(URL, encode);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 使用UTF-8对URL解码
     * @param URL 要解码的URL
     * @return 解码后的URL
     */
    public static final String decodeURL(String URL) {
        return decodeURL(URL, StringUtil.UTF8);
    }
}